<?php

namespace App\CompanyApi\Services\Jobposition;


use App\Exceptions\ApiExceptions;
use App\Models\JobpositionModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class JobpositionService
{
    public function list(int $company_id, int $cur_status = 0, string $name = '')
    {
        return JobpositionModel::query()->where('company_id', $company_id)
            ->when(in_array($cur_status, array_keys(JobpositionModel::STATUS_LIST)), function ($query) use ($cur_status) {
                return $query->where('cur_status', $cur_status);
            })->when($name, function ($query) use ($name) {
                return $query->where('position_name', 'like', '%' . $name . '%');
            })
            ->paginate();
    }

    public function detail(int $company_id,int $id)
    {
        $res =  JobpositionModel::query()->where('company_id', $company_id)->where('id',$id)->first();
        if (!$res){
            throw new ApiExceptions('职位不存在');
        }
        return $res;
    }

    /**
     * 统计
     * @param int $company_id
     * @return Builder|Model|object|null
     */
    public function statistics(int $company_id)
    {
        $res =  JobpositionModel::query()->where('company_id', $company_id)
            ->leftJoin('job_position_statistics', 'job_position.id', '=', 'job_position_statistics.job_position_id')
            ->selectRaw('sum(job_position.recruit_num) as recruit_num,sum(job_position_statistics.pv) as pv,sum(job_position_statistics.uv) as uv')
            ->first();
        $res['recruit_num'] = $res['recruit_num']??0;
        $res['pv'] = $res['pv']??0;
        $res['uv'] = $res['uv']??0;
        return $res;
    }

    /**
     * 创建
     * @param int $company_id
     * @param array $input
     * @return void
     * @throws ApiExceptions
     */
    public function store(int $company_id,array $input)
    {
        $input['company_id'] = $company_id;
        $contact_qq = $input['contact_qq'];
        $contact_phone = $input['contact_phone'];
        $contact_wechat = $input['contact_wechat'];
        $contact_dingtalk = $input['contact_dingtalk'];
        unset($input['contact_qq'], $input['contact_phone'], $input['contact_wechat'], $input['contact_dingtalk']);
        $input['cur_status'] = JobpositionModel::STATUS_CHECK_AWAIT;
        if ($input['work_time_end'])$input['work_time_end'] = "{$input['work_time_end']}:59";
        $res = JobpositionModel::query()->create($input);
        if (!$res){
            throw new ApiExceptions("职位创建失败");
        }
        if ($input['contact_type'] == JobpositionModel::CONTACT_QQ)
        {
            $res->contactQq()->createMany($contact_qq);
        }
        if ($input['contact_type'] == JobpositionModel::CONTACT_WECHAT)
        {
            $res->contactWechat()->createMany($contact_wechat);
        }
        if ($input['contact_type'] == JobpositionModel::CONTACT_DINGTALK)
        {
            $res->contactWechat()->createMany($contact_dingtalk);
        }
        if ($input['contact_type'] == JobpositionModel::CONTACT_MOBILE)
        {
            $res->contactPhone()->createMany($contact_phone);
        }
    }
    public function update(int $company_id,$id,array $input)
    {
        $position = JobpositionModel::query()->where('company_id',$company_id)->where('id',$id)->first();
         if (!$position){
             throw new ApiExceptions('职位不存在');
         }
        $contact_qq = $input['contact_qq'];
        $contact_phone = $input['contact_phone'];
        $contact_wechat = $input['contact_wechat'];
        $contact_dingtalk = $input['contact_dingtalk'];
        unset($input['contact_qq'], $input['contact_phone'], $input['contact_wechat'], $input['contact_dingtalk']);
        $input['cur_status'] = JobpositionModel::STATUS_CHECK_AWAIT;
        if ($input['work_time_end'])$input['work_time_end'] = "{$input['work_time_end']}:59";
        $res = $position->update($input);
        if (!$res){
            throw new ApiExceptions("职位更新失败");
        }
        // 更新联系信息
        if ($input['contact_type'] == JobpositionModel::CONTACT_QQ) {
            $this->syncContacts($position->contactQq(), $contact_qq);
        }

        if ($input['contact_type'] == JobpositionModel::CONTACT_WECHAT) {
            $this->syncContacts($position->contactWechat(), $contact_wechat);
        }
        
        if ($input['contact_type'] == JobpositionModel::CONTACT_DINGTALK) {
            $this->syncContacts($position->contactDingtalk(), $contact_dingtalk);
        }

        if ($input['contact_type'] == JobpositionModel::CONTACT_MOBILE) {
            $this->syncContacts($position->contactPhone(), $contact_phone);
        }
    }
    private function syncContacts($relation, array $contacts)
    {
        // 获取现有的联系信息
        $existingContacts = $relation->pluck('id')->toArray();
        $newContacts = array_filter($contacts, function ($contact) {
            return empty($contact['id']);
        });

        // 更新现有的联系信息
        foreach ($contacts as $contact) {
            if (!empty($contact['id']) && in_array($contact['id'], $existingContacts)) {
                $relation->where('id', $contact['id'])->update($contact);
            }
        }

        // 删除不在更新列表中的联系信息
        $toDelete = array_diff($existingContacts, array_column($contacts, 'id'));
        if (!empty($toDelete)) {
            $relation->whereIn('id', $toDelete)->delete();
        }

        // 创建新的联系信息
        if (!empty($newContacts)) {
            $relation->createMany($newContacts);
        }
    }
}